package com.kevin.file.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import com.kevin.file.domain.entity.SysFile;
import com.kevin.file.enums.FileSuffix;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;

/**
 * @author 张帆
 * @date 2025/6/17 15:51
 */
@Service
public class FileService {
    @Resource
    private OssFileService ossFileService;
    @Resource
    private SysFileService sysFileService;

    @Value("${oss.bucketName:loc}")
    private String bucketName = "loc";

    @SneakyThrows
    public Long uploadFile(InputStream stream, String fileName, String businessType) {
        File tempFile = Files.createTempFile(UUID.fastUUID().toString(), ".tmp").toFile();
        FileUtil.writeFromStream(stream, tempFile);

        try {
            return uploadFile(tempFile, fileName, businessType);
        } finally {
            FileUtil.del(tempFile);
        }
    }

    public Long uploadFile(File tempFile, String fileName, String businessType) {
        SysFile sysFile = new SysFile();
        sysFile.setFileType(FileSuffix.getBySuffix(fileName).getCode());
        sysFile.setFileName(fileName);
        sysFile.setFileSize(tempFile.length() / 1024);
        sysFile.setSuffix(FileSuffix.getSuffix(fileName));
        sysFile.setBusinessType(businessType);
        sysFileService.insertSysFile(sysFile);
        ossFileService.putObject(bucketName, sysFile.getFileId().toString(), tempFile);
        return sysFile.getFileId();
    }
}
